package com.jiutong;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 9tong数据源配置
 * Created by sty on 2017/2/22.
 */
@Configuration
@MapperScan(basePackages = "com.jiutong.dao.jiutong.**")
public class DataSource9tongConfiguration {
    @Bean(name="dataSource9tong")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.9tong")
    public DataSource dataSource9tong() {
        System.out.println("-------------------- 9tongDataSource init ---------------------");
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "sqlSessionFactory9tong")
    @Primary
    public SqlSessionFactory sqlSessionFactory9tong(@Qualifier("dataSource9tong") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/jiutong/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "transactionManager9tong")
    @Primary
    public DataSourceTransactionManager transactionManager9tong(@Qualifier("dataSource9tong") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionTemplate9tong")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate9tong(@Qualifier("sqlSessionFactory9tong") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
